package com.dingwen.treasure.kettle.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.dingwen.treasure.kettle.service.CategoryService;
import com.dingwen.treasure.kettle.service.FileService;
import com.dingwen.treasure.kettle.vo.CategoryVo;
import com.dingwen.treasure.kettle.vo.FileVo;
import lombok.SneakyThrows;
import org.pentaho.di.repository.RepositoryElementMetaInterface;
import org.pentaho.di.repository.StringObjectId;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 　FileServiceImpl
 * 　@author dingwen
 * 　@date 2022/8/21
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private CategoryService categoryService;

    /**
     * 获取指定目录下的转换、作业列表
     *
     * @param directoryId 目录id
     * @return {@link List}<{@link FileVo}>
     */
    @Override
    @SneakyThrows(Throwable.class)
    public List<FileVo> getFileList(String directoryId) {
        KettleDatabaseRepository databaseRepository = SpringUtil.getBean(KettleDatabaseRepository.class);
        List<RepositoryElementMetaInterface> jobAndTransformationObjects = databaseRepository.getJobAndTransformationObjects(new StringObjectId(directoryId), true);
        List<FileVo> files = new ArrayList<>(jobAndTransformationObjects.size() + 1);
        jobAndTransformationObjects.parallelStream()
                .forEach(object -> {
                    FileVo fileVo = FileVo.builder()
                            .name(object.getName())
                            .type(object.getObjectType().getTypeDescription())
                            .fileId(object.getObjectId().getId()).build();
                    files.add(fileVo);
                });
        return files;
    }

    /**
     * 获取所有文件
     *
     * @return {@link List}<{@link FileVo}>
     */
    @Override
    public List<FileVo> getAllFile() {
        List<String> categoryIds = categoryService.getAllCategory()
                .parallelStream()
                .map(CategoryVo::getId)
                .collect(Collectors.toList());
        List<FileVo> files = new ArrayList<>();
        categoryIds.parallelStream()
                .forEach(categoryId -> {
                    files.addAll(getFileList(categoryId));
                });
        return files;
    }
}
